package com.clothing.customization.repository;

import com.clothing.customization.entity.CustomerOrder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

@Repository
public interface OrderRepository extends JpaRepository<CustomerOrder, Long> {
    
    // 根据状态统计订单数量
    long countByStatus(Integer status);
    
    // 根据创建时间范围统计订单数量
    long countByCreateTimeBetween(Date startTime, Date endTime);
    
    // 获取最近4条订单
    List<CustomerOrder> findTop4ByOrderByCreateTimeDesc();
    
    // 根据用户ID查询订单列表
    List<CustomerOrder> findByUserIdOrderByCreateTimeDesc(Long userId);
    
    // 根据设计师ID查询订单列表
    List<CustomerOrder> findByDesignerIdOrderByCreateTimeDesc(Long designerId);
    
    // 根据订单编号查询
    CustomerOrder findByOrderNo(String orderNo);
    
    // 根据创建时间范围查询订单
    List<CustomerOrder> findByCreateTimeBetweenOrderByCreateTimeDesc(Date startTime, Date endTime);
    
    // 根据状态查询订单列表
    List<CustomerOrder> findByStatusOrderByCreateTimeDesc(Integer status);
    
    // 根据用户ID和状态查询订单列表
    List<CustomerOrder> findByUserIdAndStatusOrderByCreateTimeDesc(Long userId, Integer status);
    
    // 根据设计师ID和状态查询订单列表
    List<CustomerOrder> findByDesignerIdAndStatusOrderByCreateTimeDesc(Long designerId, Integer status);
    
    // 根据服装类型查询订单列表
    List<CustomerOrder> findByClothingTypeOrderByCreateTimeDesc(String clothingType);
    
    // 根据性别查询订单列表
    List<CustomerOrder> findByGenderOrderByCreateTimeDesc(String gender);
    
    // 统计用户订单数量
    long countByUserId(Long userId);
    
    // 统计设计师订单数量
    long countByDesignerId(Long designerId);
    
    // 统计用户各状态订单数量
    @Query("SELECT o.status, COUNT(o) FROM CustomerOrder o WHERE o.userId = ?1 GROUP BY o.status")
    List<Object[]> countByUserIdAndStatus(Long userId);
    
    // 统计设计师各状态订单数量
    @Query("SELECT o.status, COUNT(o) FROM CustomerOrder o WHERE o.designerId = ?1 GROUP BY o.status")
    List<Object[]> countByDesignerIdAndStatus(Long designerId);

    // 分页查询订单列表
    @Query("SELECT o FROM CustomerOrder o WHERE " +
           "(:status IS NULL OR o.status = :status) AND " +
           "(:startDate IS NULL OR o.createTime >= :startDate) AND " +
           "(:endDate IS NULL OR o.createTime <= :endDate) AND " +
           "(:keyword IS NULL OR o.orderNo LIKE CONCAT('%', :keyword, '%') OR o.productName LIKE CONCAT('%', :keyword, '%'))")
    Page<CustomerOrder> findByConditions(
            @Param("status") Integer status,
            @Param("startDate") Date startDate,
            @Param("endDate") Date endDate,
            @Param("keyword") String keyword,
            Pageable pageable);
} 